package com.example.clublesson01.login

import android.Manifest
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.bw.kf.lib_base.base.BaseActivity
import com.example.clublesson01.R
import com.example.clublesson01.databinding.ActivityChongSendCodeBinding
import java.util.Timer
import java.util.TimerTask

@Route(path = "/app/login/ChongSendCodeActivity")
class ChongSendCodeActivity : BaseActivity<ActivityChongSendCodeBinding,LoginRepo>() {
   @Autowired
   @JvmField
   var chongphone:String=""
    private var time = 60
    private lateinit var timer: Timer
    private val channelId = "default_channel_id" // 一定要写在这里
    private val notificationId = 1
    override fun iniView() {
        ARouter.getInstance().inject(this)
        binding.tvPhoneTip.text="已发送验证码至手机 $chongphone"
        viewModel.WCode(chongphone)

        binding.ivBack.setOnClickListener {
            finish()
        }

        timer = Timer()
        timer.schedule(object : TimerTask() {
            override fun run() {
                runOnUiThread {
                    if(time > 0){
                        binding.time.setText("${time}后获取验证码")
                        time--
                    }else{
                        timer.cancel()
                        binding.time.setText("点击重新获取验证码")
                        time=60;
                    }
                }
            }
        },0,1000);
        val editTexts = listOf(binding.etCode1,binding.etCode2,binding.etCode3,binding.etCode4,binding.etCode5,binding.etCode6)

        editTexts.forEachIndexed { index, editText ->
            editText.addTextChangedListener(object : TextWatcher {
                override fun afterTextChanged(s: Editable?) {
                    if (s?.length == 1 && index < editTexts.size - 1) {
                        editTexts[index + 1].requestFocus()
                    }
                    // 当用户在最后一个EditText输入框中输入一个字符时
                    if (index == editTexts.size - 1 && s?.length == 1) {
                        // 拼接所有EditText中的文本，形成完整的验证码
                        val code = editTexts.joinToString(separator = "") { it.text.toString() }
                        // 从SharedPreferences中获取之前保存的验证码
                        val codes = SPUtils.getInstance().getString("CCode")

                        // 检查用户输入的验证码长度是否与预期相符
                        if (code.length == editTexts.size) {
                            // 验证用户输入的验证码与保存的验证码是否匹配
                            if (code==codes) {
                                // 如果验证码正确，显示提示信息并允许进行下一步操作（如启动新活动）
                                ToastUtils.showLong("验证码正确")
                                viewModel.JYCode(codes.toInt(),chongphone)
                                // startActivity(...)
                            } else {
                                // 如果验证码错误，提示用户
                                ToastUtils.showLong("验证码错误")
                            }
                        } else {
                            // 如果验证码不完整，提示用户输入完整的验证码
                            ToastUtils.showLong("请输入完整的验证码")
                        }
                    }

                }

                override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

                }
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

                }
            })
        }

        //点击之后再次获取验证码
        binding.time.setOnClickListener {
            //发送验证码的网络请求
            viewModel.WCode(chongphone)
            timer = Timer()
            timer.schedule(object : TimerTask() {
                override fun run() {
                    runOnUiThread {
                        if(time > 0){
                            binding.time.setText("${time}后获取验证码")
                            time--
                        }else{
                            timer.cancel()
                            binding.time.setText("点击重新获取验证码")
                            time=60;
                        }
                    }
                }
            },0,1000);
        }
    }

    override fun iniData() {

        viewModel.successWCode.observe(this){
            ToastUtils.showLong("发送成功")
            SPUtils.getInstance().put("CCode",it.msg)
            createNotificationChannel()
            sendSimpleNotification()
        }

        viewModel.successJYCode.observe(this){
            if(it.code==200){
                ToastUtils.showLong("校验成功")
                ARouter.getInstance().build("/app/login/ChongActivity")
                    .withString("chongP",chongphone)
                    .navigation()
            }
        }
    }

    override fun getViewModel(): Class<LoginRepo> {
        return LoginRepo::class.java
    }
    override fun Layoutid(): Int {
        return R.layout.activity_chong_send_code
    }

    override fun onResume() {
        super.onResume()
        iniData()
    }
    @SuppressLint("ObsoleteSdkInt")
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = "默认通知渠道"
            val descriptionText = "这是一个演示用的通知渠道"
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel(channelId, name, importance).apply {
                description = descriptionText
            }
            val notificationManager: NotificationManager =
                getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
        }
    }
    private fun sendSimpleNotification() {
        val code = SPUtils.getInstance().getString("CCode")
        val builder = NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.icon_default_avatar) // 通知的小图标
            .setContentTitle("宗申俱乐部")
            .setContentText("验证码为：${code}<宗申俱乐部>")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        with(NotificationManagerCompat.from(this)) {
            if (ActivityCompat.checkSelfPermission(
                    this@ChongSendCodeActivity,
                    Manifest.permission.POST_NOTIFICATIONS
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return
            }
            notify(notificationId, builder.build())
        }
    }

}